package dept

import (
	"context"
	"go-zero-project/services/user/rpc/pb"

	"go-zero-project/services/user/api/internal/svc"
	"go-zero-project/services/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SelectListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeptSelectListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SelectListLogic {
	return &SelectListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SelectListLogic) DeptSelectList() (resp *types.DeptSelectListResp, err error) {
	// 1.builder rpc request
	emptyObj := pb.EmptyObj{}
	// 2.request rpc
	listResp, err := l.svcCtx.UserCenterClient.DeptSelectList(l.ctx, &emptyObj)
	if err != nil {
		return nil, err
	}
	// 3.return obj
	deptArr := listResp.DeptArr
	var deptSelectArr []types.DeptListResp
	if len(deptArr) < 1 {
		return &types.DeptSelectListResp{
			List: deptSelectArr,
		}, nil
	}
	return &types.DeptSelectListResp{
		List: l.loopMenuArr(deptArr),
	}, nil
}

func (l *SelectListLogic) loopMenuArr(arr []*pb.DeptListResp) []types.DeptListResp {
	var navArr []types.DeptListResp
	for i := 0; i < len(arr); i++ {
		infoResp := types.DeptListResp{
			DeptId:   arr[i].DeptId,
			ParentId: arr[i].ParentId,
			Name:     arr[i].Name,
			OrderNum: int(arr[i].OrderNum),
		}
		list := arr[i].SubList
		if len(list) > 0 {
			menuInArr := l.loopMenuArr(list)
			infoResp.SubList = menuInArr
		}
		navArr = append(navArr, infoResp)
	}
	return navArr
}
